import { Controller, Get, Post, Body, Param, Query, UseGuards, Request, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiBody, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
// import { RolesGuard } from '../../guards/roles.guard';
import { TencentImService } from './tencent-im.service';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../user/entities/user.entity';
const { Api: TLSSigAPIv2 } = require('tls-sig-api-v2');

@ApiTags('腾讯云IM')
@Controller('tencent-im')
@UseGuards(JwtAuthGuard)
export class TencentImController {
  private readonly logger = new Logger(TencentImController.name);
  
  constructor(
    private readonly tencentImService: TencentImService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>
  ) {}

  @Get('tencent-credentials')
  @UseGuards(JwtAuthGuard)
  async getTencentCredentials(@Request() req) {
    const user = req.user;
    
    // 从环境变量或配置中获取腾讯云应用信息
    const SDKAppID = Number(process.env.TENCENT_SDKAPPID);
    const secretKey = process.env.TENCENT_SECRETKEY;
    
    // 检查必要的配置是否存在
    if (!SDKAppID || isNaN(SDKAppID)) {
      throw new HttpException('腾讯云 SDKAppID 未配置或无效', HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    if (!secretKey) {
      throw new HttpException('腾讯云 SecretKey 未配置', HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    // 使用临时方法获取腾讯云通信ID
    const userID = this.tencentImService.getTencentUserId(user.id);
    
    try {
      this.logger.debug('TLSSigAPIv2:', TLSSigAPIv2);
      this.logger.debug('SDKAppID:', SDKAppID);
      this.logger.debug('secretKey type:', typeof secretKey);

      // 生成UserSig
      const api = new TLSSigAPIv2(SDKAppID, secretKey);
      const userSig = api.genUserSig(userID, 86400);

      return {
        userID,
        userSig,
        SDKAppID
      };
    } catch (error) {
      this.logger.error('生成UserSig错误:', error);
      throw new HttpException(`生成UserSig失败: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Post('import-user')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '导入单个用户到腾讯云IM' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        userId: { type: 'number', description: '用户ID' }
      },
      required: ['userId']
    }
  })
  async importUser(@Body() body: { userId: number }) {
    try {
      const result = await this.tencentImService.importUserToTencentIM(body.userId);
      return {
        success: true,
        message: '用户导入成功',
        data: result
      };
    } catch (error) {
      throw new HttpException({
        success: false,
        message: error.message || '用户导入失败',
      }, HttpStatus.BAD_REQUEST);
    }
  }

  @Post('import-users')
    @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '批量导入用户到腾讯云IM' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        userIds: { 
          type: 'array', 
          items: { type: 'number' },
          description: '用户ID数组' 
        }
      },
      required: ['userIds']
    }
  })
  async importUsers(@Body() body: { userIds: number[] }) {
    try {
      const result = await this.tencentImService.importUsersToTencentIM(body.userIds);
      return {
        success: true,
        message: '批量导入完成',
        data: result
      };
    } catch (error) {
      throw new HttpException({
        success: false,
        message: error.message || '批量导入失败',
      }, HttpStatus.BAD_REQUEST);
    }
  }

  @Post('import-all-users')
    @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '导入所有用户到腾讯云IM' })
  async importAllUsers() {
    try {
      const result = await this.tencentImService.importAllUsersToTencentIM();
      return {
        success: true,
        message: '所有用户导入完成',
        data: result
      };
    } catch (error) {
      throw new HttpException({
        success: false,
        message: error.message || '导入所有用户失败',
      }, HttpStatus.BAD_REQUEST);
    }
  }

  @Get('search-users')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '搜索用户（通过用户名或昵称）' })
  @ApiQuery({
    name: 'keyword',
    required: true,
    type: String,
    description: '搜索关键词（用户名或昵称）'
  })
  async searchUsers(@Query('keyword') keyword: string) {
    try {
      this.logger.debug(`搜索用户，关键词: ${keyword}`);
      
      if (!keyword || keyword.trim() === '') {
        throw new HttpException('搜索关键词不能为空', HttpStatus.BAD_REQUEST);
      }
      
      // 修改 CAST 语法，使用 MySQL 兼容的方式
      const users = await this.userRepository
        .createQueryBuilder('user')
        .where('user.username LIKE :keyword OR user.nickname LIKE :keyword OR CONVERT(user.id, CHAR) = :exactId', {
          keyword: `%${keyword}%`,
          exactId: keyword // 支持通过精确的用户ID搜索
        })
        .andWhere('user.status = :status', { status: 1 }) // 只搜索状态正常的用户
        .take(20) // 限制返回数量
        .getMany();
      
      this.logger.debug(`搜索结果: 找到 ${users.length} 个用户`);
      
      // 为每个用户生成腾讯云IM的userID并返回结果
      const result = await Promise.all(users.map(async (user) => {
        const tencentUserId = this.tencentImService.getTencentUserId(user.id);
        
        // 移除敏感信息
        const { password, ...userInfo } = user;
        
        return {
          ...userInfo,
          tencentUserId,
          userID: tencentUserId, // 兼容前端IM SDK的字段
          nick: user.nickname || user.username || `用户${user.id}` // 兼容前端IM SDK的字段
        };
      }));
      
      return result
    } catch (error) {
      this.logger.error('搜索用户失败:', error);
      throw new HttpException({
        success: false,
        message: error.message || '搜索用户失败'
      }, HttpStatus.BAD_REQUEST);
    }
  }

  @Get('get-user-info')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户信息（通过腾讯云IM的userID）' })
  @ApiQuery({
    name: 'tencentUserId',
    required: true,
    type: String,
    description: '腾讯云IM的userID'
  })
  async getUserInfo(@Query('tencentUserId') tencentUserId: string) {
    try {
      this.logger.debug(`获取用户信息，腾讯云IM的userID: ${tencentUserId}`);
      
      if (!tencentUserId) {
        throw new HttpException('腾讯云IM的userID不能为空', HttpStatus.BAD_REQUEST);
      }
      
      // 从tencentUserId中提取用户ID
      const userId = this.tencentImService.extractUserIdFromTencentUserId(tencentUserId);
      
      if (!userId) {
        throw new HttpException('无效的腾讯云IM的userID格式', HttpStatus.BAD_REQUEST);
      }
      
      // 查询用户信息
      const user = await this.userRepository.findOne({ where: { id: userId } });
      
      if (!user) {
        throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
      }
      
      // 移除敏感信息
      const { password, ...userInfo } = user;
      
      return {
        success: true,
        data: {
          ...userInfo,
          tencentUserId,
          userID: tencentUserId, // 兼容前端IM SDK的字段
          nick: user.nickname || user.username || `用户${user.id}` // 兼容前端IM SDK的字段
        }
      };
    } catch (error) {
      this.logger.error('获取用户信息失败:', error);
      throw new HttpException({
        success: false,
        message: error.message || '获取用户信息失败'
      }, HttpStatus.BAD_REQUEST);
    }
  }
}





